package com.cw.jeeyt.core.util;

import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.cw.jeeyt.service.bo.security.SecurityRoleBo;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;

/**
 * 用户session管理工具
 *
 * @author: chenw
 * @create: 2018-11-25 18:24
 */
public class SessionUtil {
    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static SecurityUserBo getSessionUser() {
        SecurityUserBo securityUserBo = null;
        Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
        if (authentication != null) {
            Object obj = authentication.getPrincipal();
            if (obj.toString()
                .equals("anonymousUser")) {
                securityUserBo = new SecurityUserBo();
                securityUserBo.setId(1000000L);
                securityUserBo.setUsername("anonymousUser");
                return securityUserBo;
            }
            securityUserBo = (SecurityUserBo) obj;
        }
        return securityUserBo;
    }

    public static Long getSessionUserId() {
        SecurityUserBo securityUserBo = null;
        Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
        if (authentication != null) {
            Object obj = authentication.getPrincipal();
            if (obj.toString()
                .equals("anonymousUser")) {
                return 1000000L;
            }
            securityUserBo = (SecurityUserBo) obj;
            return securityUserBo.getId();
        }
        return null;
    }

    /**
     * 获取用户角色
     *
     * @return
     */
    public static String getUserRoles() {
        SecurityUserBo user = getSessionUser();
        StringBuffer sb = new StringBuffer();
        List<SecurityRoleBo> roleList = user.getRoles();
        int i = 0;
        if (roleList != null && !roleList.isEmpty()) {
            for (SecurityRoleBo securityRoleBo : roleList) {
                if (i == 0) {
                    sb.append(securityRoleBo.getId());
                } else {
                    sb.append("," + securityRoleBo.getId());
                }
                i++;
            }
        }
        return sb.toString();
    }
}
